import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:intl/intl.dart';
import '../services/upload/core/upload_manager.dart';
import '../models/chunk_upload.dart';
import '../screens/upload_tasks_screen.dart';
import '../services/file_service.dart';

class PhotoPickerPage extends StatefulWidget {
  final int directoryId;
  final VoidCallback? onUploadComplete;

  const PhotoPickerPage({Key? key, this.directoryId = 0, this.onUploadComplete})
    : super(key: key);

  @override
  State<PhotoPickerPage> createState() => _PhotoPickerPageState();
}

class _PhotoPickerPageState extends State<PhotoPickerPage> {
  bool _showOnlyUploaded = false;
  bool _isLoading = true;
  bool _isUploading = false; // 添加上传状态标志
  double _uploadProgress = 0.0; // 添加上传进度

  // 照片管理器相关变量
  List<AssetPathEntity> _albums = [];
  List<AssetEntity> _mediaList = [];
  final Map<String, List<AssetEntity>> _dateGroupedMedia = {};
  final Set<AssetEntity> _selectedAssets = {};

  // 缩略图缓存
  final Map<String, Uint8List?> _thumbnailCache = {};

  @override
  void initState() {
    super.initState();
    _requestPermissionAndLoadPhotos();
  }

  @override
  void dispose() {
    // 清理缓存
    _thumbnailCache.clear();
    super.dispose();
  }

  // 请求权限并加载照片
  Future<void> _requestPermissionAndLoadPhotos() async {
    // 请求权限
    final PermissionState result = await PhotoManager.requestPermissionExtend();
    if (result.isAuth) {
      // 权限获取成功，加载照片
      await _loadAlbums();
    } else {
      // 显示权限拒绝提示
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('无法访问相册，请在设置中允许访问照片')));
      }
    }
  }

  // 加载相册
  Future<void> _loadAlbums() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 获取所有相册
      _albums = await PhotoManager.getAssetPathList(
        type: RequestType.image, // 仅加载图片
      );

      if (_albums.isNotEmpty) {
        // 默认选择第一个相册（通常是"全部照片"）
        await _loadAssetsFromAlbum(_albums.first);
      }
    } catch (e) {
      debugPrint('加载相册出错: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 从指定相册加载照片
  Future<void> _loadAssetsFromAlbum(AssetPathEntity album) async {
    setState(() {
      _isLoading = true;
      _mediaList = [];
      _dateGroupedMedia.clear();
    });

    try {
      // 获取相册中的所有照片
      final List<AssetEntity> assets = await album.getAssetListRange(
        start: 0,
        end: 1000, // 最多加载1000张照片
      );

      _mediaList = assets;

      // 按日期分组
      _groupMediaByDate();

      // 预加载缩略图
      _preloadThumbnails(assets);
    } catch (e) {
      debugPrint('加载照片出错: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 预加载缩略图
  Future<void> _preloadThumbnails(List<AssetEntity> assets) async {
    for (final asset in assets.take(20)) {
      // 只预加载前20张以避免内存问题
      _getThumbnail(asset);
    }
  }

  // 获取缩略图（带缓存）
  Future<Uint8List?> _getThumbnail(AssetEntity asset) async {
    final String cacheKey = asset.id;

    // 检查缓存
    if (_thumbnailCache.containsKey(cacheKey)) {
      return _thumbnailCache[cacheKey];
    }

    // 获取缩略图
    try {
      final thumbnailData = await asset.thumbnailDataWithSize(
        const ThumbnailSize(300, 300),
        quality: 95, // 提高质量
      );

      // 存入缓存
      _thumbnailCache[cacheKey] = thumbnailData;
      return thumbnailData;
    } catch (e) {
      debugPrint('获取缩略图失败: $e');
      return null;
    }
  }

  // 按日期对照片进行分组
  void _groupMediaByDate() {
    _dateGroupedMedia.clear();

    for (final AssetEntity asset in _mediaList) {
      // 将日期格式化为 "yyyy-MM-dd"
      final String dateStr = DateFormat(
        'yyyy-MM-dd',
      ).format(asset.createDateTime);

      if (!_dateGroupedMedia.containsKey(dateStr)) {
        _dateGroupedMedia[dateStr] = [];
      }

      _dateGroupedMedia[dateStr]!.add(asset);
    }
  }

  // 切换选择照片 - 使用更局部的更新方式
  void _toggleSelectAsset(AssetEntity asset) {
    final bool wasSelected = _selectedAssets.contains(asset);

    // 避免重复setState导致的闪烁
    if (wasSelected) {
      _selectedAssets.remove(asset);
    } else {
      _selectedAssets.add(asset);
    }

    // 只有在底部状态栏需要更新时才调用setState
    setState(() {
      // 空实现，只触发底部选择计数的更新
    });
  }

  // 全选/取消全选
  void _toggleSelectAll() {
    setState(() {
      if (_selectedAssets.isEmpty) {
        // 全选
        for (final asset in _mediaList) {
          _selectedAssets.add(asset);
        }
      } else {
        // 取消全选
        _selectedAssets.clear();
      }
    });
  }

  // 格式化显示日期
  String _formatDisplayDate(String dateStr) {
    final DateTime now = DateTime.now();
    final DateTime yesterday = DateTime(now.year, now.month, now.day - 1);
    final DateTime date = DateFormat('yyyy-MM-dd').parse(dateStr);

    if (DateFormat('yyyy-MM-dd').format(now) == dateStr) {
      return '今天';
    } else if (DateFormat('yyyy-MM-dd').format(yesterday) == dateStr) {
      return '昨天';
    } else {
      return DateFormat('M月d日').format(date);
    }
  }

  // 添加上传照片的方法
  Future<void> _uploadSelectedPhotos() async {
    if (_selectedAssets.isEmpty) return;

    // 先关闭当前页面，再跳转到上传任务页面
    Navigator.of(context).pop();
    Navigator.of(context, rootNavigator: true).push(
      CupertinoPageRoute(
        builder:
            (context) => UploadTasksScreen(
              onUploadComplete:
                  widget.onUploadComplete ??
                  () {
                    // 如果没有传入回调，则使用默认的通知方式
                    FileService.notifyFileListUpdated();
                  },
            ),
      ),
    );

    try {
      final uploadManager = UploadManager();
      final tasks = <UploadTask>[];

      for (final asset in _selectedAssets) {
        try {
          // 获取实际文件路径
          final file = await asset.file;
          if (file == null) {
            throw Exception('无法获取文件');
          }

          // 添加上传任务，传递当前目录ID
          final task = await uploadManager.addFileUpload(
            file.path,
            directoryId: widget.directoryId,
          );
          tasks.add(task);
        } catch (e) {
          debugPrint('准备上传照片失败: $e');
        }
      }

      // 清空选择
      _selectedAssets.clear();
    } catch (e) {
      debugPrint('上传过程出错: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text('最近项目', style: TextStyle(color: Colors.black)),
        actions: [
          TextButton(
            onPressed: _toggleSelectAll,
            child: Text(_selectedAssets.isEmpty ? '全选' : '取消全选'),
          ),
        ],
      ),
      body: Column(
        children: [
          // 开关控制
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                const Text('仅显示未上传'),
                const Spacer(),
                Switch(
                  value: _showOnlyUploaded,
                  onChanged: (value) {
                    setState(() {
                      _showOnlyUploaded = value;
                    });
                  },
                ),
              ],
            ),
          ),

          // 加载指示器
          if (_isLoading)
            const Expanded(child: Center(child: CircularProgressIndicator()))
          else if (_dateGroupedMedia.isEmpty)
            const Expanded(child: Center(child: Text('没有找到照片')))
          else
            // 日期分组列表
            Expanded(
              child: ListView.builder(
                itemCount: _dateGroupedMedia.length,
                itemBuilder: (context, index) {
                  final String dateStr = _dateGroupedMedia.keys.elementAt(
                    index,
                  );
                  final List<AssetEntity> assetsInDate =
                      _dateGroupedMedia[dateStr]!;
                  return _buildDateGroup(dateStr, assetsInDate);
                },
              ),
            ),

          // 底部上传按钮
          Container(
            padding: const EdgeInsets.all(16),
            decoration: const BoxDecoration(
              color: Colors.white,
              border: Border(top: BorderSide(color: Colors.grey, width: 0.5)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (_isUploading)
                  LinearProgressIndicator(
                    value: _uploadProgress,
                    backgroundColor: Colors.grey[200],
                    valueColor: const AlwaysStoppedAnimation<Color>(
                      Colors.blue,
                    ),
                  ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Text('已选择: ${_selectedAssets.length}'),
                    const Spacer(),
                    ElevatedButton(
                      onPressed:
                          _selectedAssets.isEmpty || _isUploading
                              ? null
                              : _uploadSelectedPhotos,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        foregroundColor: Colors.white,
                        disabledBackgroundColor: Colors.grey.shade300,
                      ),
                      child: Text(_isUploading ? '上传中...' : '上传'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateGroup(String dateStr, List<AssetEntity> assets) {
    // 使用 RepaintBoundary 减少重绘
    return RepaintBoundary(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              _formatDisplayDate(dateStr),
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          LayoutBuilder(
            builder: (context, constraints) {
              final double itemWidth =
                  (constraints.maxWidth - 24) / 4; // 4列，考虑间距
              return GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: const EdgeInsets.symmetric(horizontal: 8),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 8,
                  crossAxisSpacing: 8,
                ),
                itemCount: assets.length,
                itemBuilder: (context, index) {
                  final asset = assets[index];
                  // 使用 ValueKey 确保 Widget 能正确识别
                  return PhotoItem(
                    key: ValueKey(asset.id),
                    asset: asset,
                    isSelected: _selectedAssets.contains(asset),
                    onToggle: _toggleSelectAsset,
                    getThumbnail: _getThumbnail,
                    size: itemWidth,
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }
}

// 照片项组件 - 有状态组件
class PhotoItem extends StatefulWidget {
  final AssetEntity asset;
  final bool isSelected;
  final Function(AssetEntity) onToggle;
  final Future<Uint8List?> Function(AssetEntity) getThumbnail;
  final double size;

  const PhotoItem({
    Key? key,
    required this.asset,
    required this.isSelected,
    required this.onToggle,
    required this.getThumbnail,
    required this.size,
  }) : super(key: key);

  @override
  State<PhotoItem> createState() => _PhotoItemState();
}

class _PhotoItemState extends State<PhotoItem> {
  late bool _isSelected;
  Uint8List? _cachedThumbnail;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _isSelected = widget.isSelected;
    _loadThumbnail();
  }

  @override
  void didUpdateWidget(PhotoItem oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.isSelected != widget.isSelected) {
      _isSelected = widget.isSelected;
    }
  }

  Future<void> _loadThumbnail() async {
    _isLoading = true;
    try {
      final thumbnail = await widget.getThumbnail(widget.asset);
      if (mounted) {
        setState(() {
          _cachedThumbnail = thumbnail;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _handleTap() {
    // 先在本地更新状态，减少延迟感
    setState(() {
      _isSelected = !_isSelected;
    });
    // 通知父组件
    widget.onToggle(widget.asset);
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: GestureDetector(
        onTap: _handleTap,
        child: SizedBox(
          width: widget.size,
          height: widget.size,
          child: Stack(
            children: [
              Container(
                width: widget.size,
                height: widget.size,
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: _buildThumbnail(),
                ),
              ),
              Positioned(
                right: 4,
                top: 4,
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 150),
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    color: _isSelected ? Colors.blue : Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(
                      color: _isSelected ? Colors.blue : Colors.grey,
                      width: 1.5,
                    ),
                  ),
                  child:
                      _isSelected
                          ? const Center(
                            child: Icon(
                              Icons.check,
                              color: Colors.white,
                              size: 16,
                            ),
                          )
                          : null,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildThumbnail() {
    if (_isLoading) {
      return Container(
        color: Colors.grey[300],
        child: const Center(
          child: SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
        ),
      );
    }

    if (_cachedThumbnail == null) {
      return Container(
        color: Colors.grey[300],
        child: const Center(
          child: Icon(Icons.broken_image, color: Colors.grey),
        ),
      );
    }

    return Image.memory(
      _cachedThumbnail!,
      width: widget.size,
      height: widget.size,
      fit: BoxFit.cover,
      gaplessPlayback: true,
      isAntiAlias: true,
      filterQuality: FilterQuality.medium,
    );
  }
}
